from typing import List

from pydantic import BaseModel, Field, root_validator
from hashlib import md5


class _AttributeValueBaseModel(BaseModel):
    attribute_value: str = Field(..., description="属性值", max_length=32)
    attribute_code: str = Field(None, description="属性值的md5加密之后的结果")

    @root_validator()
    def validate_root(cls, attrs: dict):
        attribute_value = attrs.get("attribute_value")
        attribute_code = md5(attribute_value.encode("utf-8")).hexdigest()
        attrs["attribute_code"] = attribute_code
        return attrs


class AddNewAttributeValueModel(_AttributeValueBaseModel):
    ...


class UpdateAttributeValueRequestModel(_AttributeValueBaseModel):
    ...


class AddNewAttributeModel(BaseModel):
    attribute_name: str = Field(..., description="属性名", max_length=32)
    attribute_value_list: List[AddNewAttributeValueModel] = Field(..., description="属性值")
    attribute_code: str = Field(None, description="属性名md5加密之后的结果")

    @root_validator()
    def validate_root(cls, attrs: dict):
        attribute_name = attrs.get("attribute_name")
        attribute_code = md5(attribute_name.encode("utf-8")).hexdigest()
        attrs["attribute_code"] = attribute_code
        return attrs


class UpdateAttributeRequestModel(BaseModel):
    attribute_name: str = Field(..., description="属性名", max_length=32)
    attribute_code: str = Field(None, description="属性名md5加密之后的结果")

    @root_validator()
    def validate_root(cls, attrs: dict):
        attribute_name = attrs.get("attribute_name")
        attribute_code = md5(attribute_name.encode("utf-8")).hexdigest()
        attrs["attribute_code"] = attribute_code
        return attrs